@(roadmap: Roadmap, measures: List[(Measure, RoadmapMeasure)], discounts: List[RoadmapDiscount], editPlanForm: Form[RoadmapPlan], allMeasures: List[Measure])

@import helper._

@measureName(measureId: String) = @{
	allMeasures.find(_.id.get.toString == measureId) match {
		case None => ""
		case Some(x) => x.name
	}
}

@measureStatus(value: Option[String]) = @{
  if (value.getOrElse("").isEmpty) {
    "In-progress"
  } else {
    value
  }
}

@inputDefaultNumbers(value: Option[String]) = @{
  if (value.getOrElse("").isEmpty) {
    0.0
  } else {
    value
  }
}

@measureGroup(field: Field, className: String = "measure") = {
  <tr class="@className">
		<td style="display:none;">
      <input type="hidden" id=@(field.id + "_roadmapId")
        name=@(field.name + ".roadmapId")
        value="@editPlanForm("customerId").value" />
    </td>
    <td>
			<input type="hidden" id=@(field.id + "_status_in") 
				name=@(field.name + ".status") 
				value="@measureStatus(field("status").value)" />

      <a href="#" class="status-fld" 
      id="@(field.id + "_status")"
      data-type="checklist" 
      data-pk="@field.id" 
      data-title="Select status"
      data-value="@measureStatus(field("status").value)">
        @measureStatus(field("status").value)
      </a>
		</td>
    <td>
			<input type="hidden" id=@(field.id + "_roadmapMeasureId_in") 
				name=@(field.name + ".roadmapMeasureId") 
				value='@field("roadmapMeasureId").value' />
			<a href="#" class="measure-fld" 
			id="@(field.id + "_roadmapMeasureId")"
      data-type="select" 
			data-pk="@field.id" 
			data-title="Select Measure">
				@measureName(field("roadmapMeasureId").value.getOrElse(""))
			</a>
		</td>
    <td>
    	<input type="hidden" id=@(field.id + "_installCost_in") 
    		name=@(field.name + ".installCost") 
    		value="@inputDefaultNumbers(field("installCost").value)" />
      <a id="@(field.id + "_installCost")" href="#" class="cost-fld" 
          data-type="text" data-pk="@field.id" data-title="Enter Install Cost">
        @field("installCost").value
      </a>
    </td>
    <td>
    	<input type="hidden" id=@(field.id + "_savingCost_in") 
    		name=@(field.name + ".savingCost") 
    		value="@inputDefaultNumbers(field("savingCost").value)" />
      <a id="@(field.id + "_savingCost")" href="#" class="saving-fld" data-type="text" 
          data-pk="@field.id" data-title="Enter Saving Cost">
        @field("savingCost").value
      </a>
    </td>
    <td>
    	<input type="hidden" id=@(field.id + "_savingCO2_in") 
    		name=@(field.name + ".savingCO2") 
    		value="@inputDefaultNumbers(field("savingCO2").value)" />
      <a id="@(field.id + "_savingCO2")" href="#" class="co2-fld" data-type="text" 
          data-pk="@field.id" data-title="Enter CO2 Saving">
        @field("savingCO2").value
      </a>
    </td>
    <td>
      <a id="@(field.id + "_remove")" class="removeMeasure btn pull-right">
        <span class="glyphicon glyphicon-trash"></span>
      </a>
    </td>
  </tr>
}

@discountGroup(field: Field, className: String = "discount") = {
  <tr class="@className">
    <td style="display:none;">
      <input type="hidden" id=@(field.id + "_roadmapId")
        name=@(field.name + ".roadmapId")
        value="@editPlanForm("customerId").value" />
    </td>
    <td>
      <input type="hidden" id=@(field.id + "_name_in") 
        name=@(field.name + ".name") 
        value="@field("name").value" />
      <a id="@(field.id + "_name")" href="#" class="discount-name-fld" 
          data-type="text" data-pk="@field.id" data-title="Enter Name">
        @field("name").value
      </a>
    </td>
    <td>
      <input type="hidden" id=@(field.id + "_notes_in") 
        name=@(field.name + ".notes") 
        value="@field("notes").value" />
      <a id="@(field.id + "_notes")" href="#" class="discount-notes-fld" data-type="text" 
          data-pk="@field.id" data-title="Enter Notes">
        @field("notes").value
      </a>
    </td>
    <td>
      <input type="hidden" id=@(field.id + "_discount_in") 
        name=@(field.name + ".discount") 
        value="@inputDefaultNumbers(field("discount").value)" />
      <a id="@(field.id + "_discount")" href="#" class="discount-value-fld" data-type="text" 
          data-pk="@field.id" data-title="Enter Discount Value">
        @field("discount").value
      </a>
    </td>
    <td>
      <a id="@(field.id + "_remove")" class="removeDiscount btn pull-right">
        <span class="glyphicon glyphicon-trash"></span>
      </a>
    </td>
  </tr>
}

<div class="panel-body edit-plan">

  @if(editPlanForm.hasErrors) {
    <div class="alert-message error">
        <p><strong>Oops</strong> Error occured </p>
        <dl>
            @for(error <- editPlanForm.errors) {
              <dt>
                  Field: @error.key
              </dt>
              <dd>
                Message: @error.message
              </dd>
            }
        </dl>
    </div>
  }

  @helper.form(action = routes.Roadmaps.editPlan) {
    <input type="hidden" name="customerId" value='@editPlanForm("customerId").value' />  

    <fieldset style="padding-bottom:20px;">
      <legend>Measures</legend>
        
      <div id="measures" class="table-responsive">
      
        <table id="measureEditTbl" class="table table-condensed">
          <thead>  
            <tr>  
              <th style="display:none;"></th>
              <th class="col-sm-1">Status</th>  
              <th class="col-sm-3">Measure</th>  
              <th class="col-sm-2">Cost</th>  
              <th class="col-sm-2">Saving</th>
              <th class="col-sm-2">CO2 Saving</th>
              <th class="col-sm-1"></th>
            </tr>  
          </thead>  
          <tbody>

            @repeat(editPlanForm("measures"), min = 0) { measure =>
          
               @measureGroup(measure)

            }

            @**
            * Keep an hidden block that will be used as template for Javascript copy code
            **@
            @measureGroup(
                editPlanForm("measures[x]"),
                className = "measure-template"
            )

          </tbody>
        </table>

        <a class="add-measure btn btn-default success">Add another measure</a>
        
      </div>
        
    </fieldset>

    <fieldset style="padding-bottom:20px;">
      <legend>Discounts</legend>
      
      <div id="discounts" class="table-responsive">
      
        <table id="discountEditTbl" class="table table-condensed">
              <th style="display:none;"></th>
              <th class="col-sm-3">Name</th>  
              <th class="col-sm-4">Notes</th>  
              <th class="col-sm-2">Discount</th>  
            </tr>  
          </thead>  
          <tbody>

            @repeat(editPlanForm("discounts"), min = 0) { discount =>
          
               @discountGroup(discount)

            }

            @**
            * Keep an hidden block that will be used as template for Javascript copy code
            **@
            @discountGroup(
                editPlanForm("discounts[x]"),
                className = "discount-template"
            )

          </tbody>
        </table>

        <a class="add-discount btn btn-default success">Add another discount</a>
      
      </div>
        
    </fieldset>
    
    <div>
        <input type="submit" class="btn primary" value="Submit" />
        <a href="#" class="cancel-edit-lnk btn">Cancel</a>
    </div>
      
  }	
</div>

<script type="text/javascript" charset="utf-8">
	$(document).ready(function() {
    $('a.cancel-edit-lnk').click(function() {
      $('.edit-plan').hide();
      $('.plan-details').show();
      $('.edit-plan-lnk').show();
      $('#tipsPnl').show();
      $('#socialMediaPnl').show();
    });

		refreshEditableFields();

		addEventToRemoveLinks();

    $('.add-measure').click(function(e) {
		  var template = $('.measure-template');
    	var lastRow = $('#measureEditTbl tr:last');
    	lastRow.after('<tr class="measure">' + template.html() + '</tr>');
    	renumberMeasures();
    	refreshEditableFields();
    	addEventToRemoveLinks();
    });

    $('.add-discount').click(function(e) {
      var template = $('.discount-template');
      var lastRow = $('#discountEditTbl tr:last');
      lastRow.after('<tr class="discount">' + template.html() + '</tr>');
      renumberDiscounts();
      refreshEditableFields();
      addEventToRemoveLinks();
    });

		// -- renumber fields

		// Rename fields to have a coherent payload like:
		//
		// measures[0].label
		// measures[0].email
		// measures[0].phones[0]
		// measures[0].phones[1]

		var renumberMeasures = function() {
			$('.measure').each(function(i) {
			    $('input', this).each(function() {
			        $(this).attr('name', $(this).attr('name').replace(/measures\[.+?\]/g, 'measures[' + i + ']'));
              $(this).attr('id', $(this).attr('id').replace(/measures_.+?__/g, 'measures_' + i + '__'));
			    })
          $('a', this).each(function() {
              $(this).attr('id', $(this).attr('id').replace(/measures_.+?__/g, 'measures_' + i + '__'));
          })
			})
		}

    var renumberDiscounts = function() {
      $('.discount').each(function(i) {
          $('input', this).each(function() {
              $(this).attr('name', $(this).attr('name').replace(/discounts\[.+?\]/g, 'discounts[' + i + ']'));
              $(this).attr('id', $(this).attr('id').replace(/discounts_.+?__/g, 'discounts_' + i + '__'));
          })
          $('a', this).each(function() {
              $(this).attr('id', $(this).attr('id').replace(/discounts_.+?__/g, 'discounts_' + i + '__'));
          })
      })
    } 
	});

  function setInputValue(lnk, value) {
    var d = new $.Deferred;
    var inputId = $(lnk).attr('id') + "_in";
    $("#" + inputId).val(value);
    d.resolve();
    return d.promise();
  }

	function refreshEditableFields() {
		$.fn.editable.defaults.mode = 'inline';

    $('.status-fld').editable({
      emptytext: "In-progress",
      emptyclass: "",
      source: [
        {value: 'Completed', text: 'Completed'}
      ],
      url: function(params) {
        if (params.value != "Completed") {
          return setInputValue(this, "In-progress");  
        } else {
          return setInputValue(this, params.value);
        }  
      }
    });

		$('.measure-fld').editable( {
			source: [
				@for( m <- allMeasures) { 
          {value: @m.id, text: '@m.name'},
        }  
       ],
      url: function(params) {
        return setInputValue($(this), params.value);
      } 
		});

		$('.cost-fld').editable({
      emptytext: "0",
      display: function(value) {
      	if(value != '' && !isNaN(value)) {
          $(this).text('£' + parseFloat(value).toFixed(2));
        }
      },
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });

    $('.saving-fld').editable({
      emptytext: "0",
      display: function(value) {
        if(value != '' && !isNaN(value)) {
          $(this).text('£' + parseFloat(value).toFixed(2));
        }
      },
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });

    $('.co2-fld').editable({
      emptytext: "0",
      display: function(value) {
        if(value != '' && !isNaN(value)) {
          $(this).text(parseFloat(value).toFixed(2) + ' kWh/p.a.');
        }  
      },
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });

    // discount fields
    $('.discount-name-fld').editable({
      emptyclass: "",
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });

    $('.discount-notes-fld').editable({
      emptyclass: "",
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });


   $('.discount-value-fld').editable({
      emptytext: "0",
      display: function(value) {
        if(value != '' && !isNaN(value)) {
          $(this).text('£' + parseFloat(value).toFixed(2));
        }
      },
      url: function(params) {
        return setInputValue(this, params.value);
      } 
    });


	}

	function addEventToRemoveLinks() {
		$('.removeMeasure').click(function(e) {
		  $(this).parents('.measure').remove();
	    renumberMeasures();
	  })	

    $('.removeDiscount').click(function(e) {
      $(this).parents('.discount').remove();
      renumberDiscounts();
    })  
	}

</script> 

